 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=43 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:38 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Recovering resources
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='finalize,finally,resources,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Recovering resources</div>

<div class='main-body'>
 
<br>Expensive resources should be reclaimed as soon as possible, by an
explict call to a clean up method defined for this purpose. If this is
not done, then system performance can degrade.
<p>Resources include :
<ul>
<li>
input-output streams</li>

<li>
database result sets, statements, and connections</li>

<li>
threads</li>

<li>
graphic resources</li>

<li>
sockets</li>
</ul>
Resources which are created locally within a method must be cleaned up
within the same method, by calling a method appropriate to the resource
itself, such as <tt>close</tt> or <tt>dispose</tt>. This is usually done
in a <tt>finally</tt> clause.
<p>For the case of a resource which is a <i>field</i>, however, there is
more work to do :
<ul>
<li>
implement a clean up method which the user must call when finished with
the object, with a name such as <tt>close</tt> or <tt>dispose</tt></li>

<li>
the caller should be able to query an object to see if its clean up method
has been executed</li>

<li>
non-<tt>private</tt> methods (other than the clean up method itself) should
throw an <tt>IllegalStateException</tt> if the clean up method has already
been invoked</li>

<li>
as a safety net, implement <tt>finalize</tt> to call the clean up method
as well; if the user of the class neglects to call the clean up method,
then this may allow recovery of the resource by the system</li>

<li>
<a href="TopicAction691e-2.html">never rely</a> solely on <tt>finalize</tt></li>
</ul>
This example shows a class which retains a database connection during its
lifetime. (This example is artificial. Actually writing such a class would not seem necessary in practice, 
since connection pools already perform such clean up in the background.)
<br>
<PRE>

<span class='keyword'>import</span> java.sql.*;
<span class='keyword'>import</span> java.text.*;
<span class='keyword'>import</span> java.util.*;

<span class='comment'>/**
* This class has an enforced life cycle: after destroy is
* called, no useful method can be called on this object
* without throwing an IllegalStateException.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> DbConnection {

  <span class='keyword'>public</span> DbConnection () {
    <span class='comment'>//build a connection and assign it to a field
</span>    <span class='comment'>//elided.. fConnection = ConnectionPool.getInstance().getConnection();
</span>  }

  <span class='comment'>/**
  * Ensure the resources of this object are cleaned up in an orderly manner.
  *
  * The user of this class must call destroy when finished with
  * the object. Calling destroy a second time is permitted, but is
  * a no-operation.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> destroy() <span class='keyword'>throws</span> SQLException {
    <span class='keyword'>if</span> (fIsDestroyed) {
       <span class='keyword'>return</span>;
    }
    <span class='keyword'>else</span>{
      <span class='keyword'>if</span> (fConnection != <span class='keyword'>null</span>) fConnection.close();
      fConnection = <span class='keyword'>null</span>;
      <span class='comment'>//flag that destory has been called, and that
</span>      <span class='comment'>//no further calls on this object are valid
</span>      fIsDestroyed = <span class='keyword'>true</span>;
    }
  }

  <span class='comment'>/**
  * Fetches something from the db.
  *
  * This is an example of a non-private method which must ensure that
  * &lt;code&gt;destroy&lt;/code&gt; has not yet been called
  * before proceeding with execution.
  */</span>
  <span class='keyword'>synchronized</span> <span class='keyword'>public</span> Object fetchBlah (String aId) <span class='keyword'>throws</span> SQLException {
    validatePlaceInLifeCycle();
    <span class='comment'>//..elided
</span>    <span class='keyword'>return</span> <span class='keyword'>null</span>;
  }

  <span class='comment'>/**
  * If the user fails to call &lt;code&gt;destroy&lt;/code&gt;, then implementing
  * finalize will act as a safety net, but this is not foolproof.
  */</span>
  <span class='keyword'>protected</span> <span class='keyword'>void</span> finalize() <span class='keyword'>throws</span> Throwable{
    <span class='keyword'>try</span>{
      destroy();
    }
    <span class='keyword'>finally</span>{
      <span class='keyword'>super</span>.finalize();
    }
  }

  <span class='comment'>/**
  * Allow the user to determine if &lt;code&gt;destroy&lt;/code&gt; has been called.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>boolean</span> isDestoyed() {
    <span class='keyword'>return</span> fIsDestroyed;
  }

  <span class='comment'>// PRIVATE //
</span>
  <span class='comment'>/**
  * Connection which is constructed and managed by this object.
  * The user of this class must call destroy in order to release this
  * Connection resource.
  */</span>
  <span class='keyword'>private</span> Connection fConnection;

  <span class='comment'>/**
  * This object has a specific "life cycle", such that methods must be called
  * in the order: others + destroy. fIsDestroyed keeps track of the lifecycle,
  * and non-private methods must check this value at the start of execution.
  * If destroy is called more than once, a no-operation occurs.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> fIsDestroyed;

  <span class='comment'>/**
  * Once &lt;code&gt;destroy&lt;/code&gt; has been called, the services of this class
  * are no longer available.
  *
  * @throws IllegalStateException if &lt;code&gt;destroy&lt;/code&gt; has
  * already been called.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>void</span> validatePlaceInLifeCycle(){
    <span class='keyword'>if</span> ( fIsDestroyed ) {
      String message = <span class='literal'>"Method cannot be called after destroy has been called."</span>;
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalStateException(message);
    }
  }
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActiona0d7-2.html?Id=8'>Always close streams</a> <br>
 
  
  <a href='TopicAction691e-2.html?Id=24'>Never rely on finalize</a> <br>
 
  
  <a href='TopicActione028-2.html?Id=25'>Finally and catch</a> <br>
 
  
  <a href='TopicAction799b-2.html?Id=127'>Get database connection</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='43'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=43 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:38 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
